package tgc.rj.garbage.activity;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android_serialport_api.SerialPort;
import tgc.rj.garbage.R;
import tgc.rj.garbage.custom.IConstant;
import tgc.rj.garbage.custom.ToastUtils;

public class TestActivity extends AppCompatActivity implements View.OnClickListener, Runnable {
    private Button btn_begin;
    private Button btn_end;
    private TextView txt_input;
    public SerialPort serialPort = null;
    public InputStream inputStream = null;
    public OutputStream outputStream = null;
    public boolean flag = false;
    private byte txh = 1;
    private Spinner spinner_hdh;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        btn_begin = findViewById(R.id.btn_begin);
        btn_end = findViewById(R.id.btn_end);
        btn_begin.setOnClickListener(this);
        btn_end.setOnClickListener(this);
        txt_input = findViewById(R.id.tv_input_text);
        spinner_hdh = findViewById(R.id.spinner_hdh);

        beginRead(); //打开下位机串口


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_begin:
                beginRead();
                break;
            case R.id.btn_end:
                endRead();
                break;
        }
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (txh > 255) {
                txh = 1;
            }
            String str = msg.getData().getString("data");
            String hdhStr = spinner_hdh.getSelectedItem().toString();
            Integer hdhint = Integer.parseInt(hdhStr);
            byte hdhbyte = (byte) hdhint.intValue();
            ToastUtils.toastUtils(TestActivity.this, "货道号字符串表示：" + hdhStr + "货道号字节表示：" + hdhbyte);
            byte[] bytes = new byte[10];
            bytes[0] = (byte) 0xfa;
            bytes[1] = (byte) 0xfb;
            bytes[2] = 0x06;
            bytes[3] = 0x05;
            bytes[4] = txh;
            bytes[5] = 0x01;
            bytes[6] = 0x01;
            bytes[7] = 0x00;
            bytes[8] = hdhbyte;
            bytes[9] = xor(bytes);

            txt_input.setText(txt_input.getText().toString() + str + "\n");
            for (int i = 1; i <= 5; i++) {
                if (str.equals("fa fb 41 00 40")) {
                    sendSerialPort(bytes);
                } else if (str.equals("fa fb 42 00 43")) {
                    endRead();
                    txh++;
                    break;
                }
            }
        }
    };

    //关闭串口
    private void endRead() {
        closeSerialPort();
    }

    //开启串口
    private void beginRead() {
        openSrialPort();
        new Thread(this).start();
    }

    //打开串口工具类
    public void openSrialPort() {
        try {
            serialPort = new SerialPort(new File("/dev/" + IConstant.PORT), IConstant.BAUDRATE, 0);
            //获取打开的串口中的输入输出流，以便于串口数据的收发
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     *关闭串口输入输出流
     */
    public void closeSerialPort() {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            flag = false;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /***
     * 发送串口数据
     * @param data
     */
    public void sendSerialPort(byte[] data) {
        try {
            outputStream.write(data);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     * 开启线程接收下位机数据
     */
    @Override
    public void run() {
        byte[] readData = new byte[1024];
        byte[] x = new byte[5];
        int idx = 0;
        while (flag) {
            if (inputStream == null) {
                return;
            }
            try {
                int size = inputStream.read(readData);
                if (readData[0] == (byte) 0xfa) {
                    x = new byte[5];
                    idx = 0;
                }
                if (idx + size > 5) {
                    x = new byte[5];
                    idx = 0;
                    continue;
                } else {
                    for (int i = 0; i < size; i++) {
                        x[idx++] = readData[i];
                    }
                }
                if (idx == 5) {
                    String str = bytesToHexString(x);
                    str = str.substring(0, str.length() - 1);
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("data", str);
                    message.setData(bundle);
                    handler.sendMessage(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        serialPort.close();
    }

    public String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
            stringBuilder.append(" ");
        }
        return stringBuilder.toString();
    }

    /***
     * 异或校验算法
     * @param a
     * @return
     */
    public byte xor(byte[] a) {
        byte temp = a[0];
        for (int i = 1; i < a.length - 1; i++) {
            temp ^= a[i];
        }
        return temp;
    }

}
